package com.tg.service.eventbus2.springconfig;

import com.google.common.collect.Lists;
import com.tg.service.eventbus2.Component;
import com.tg.service.eventbus2.ComponentBus;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class EventBusFactoryBean implements FactoryBean<ComponentBus>, ApplicationContextAware, BeanNameAware {

    private ApplicationContext context;

    private String beanName;

    private static final Map<String, List<String>> BEAN_NAME_2_CP = new HashMap<>();

    static {
        BEAN_NAME_2_CP.put("LoginEventBusFactoryBean", Lists.newArrayList(
                "FirstLoginCp",
                "CheckGroupCp"
        ));

        BEAN_NAME_2_CP.put("PayEventBusFactoryBean", Lists.newArrayList(
                "FirstLoginCp"
        ));
    }

    @Override
    public ComponentBus getObject() throws Exception {
        List<Component> cps = BEAN_NAME_2_CP.get(this.beanName)
                .stream()
                .map(name -> (Component) this.context.getBean(name))
                .collect(Collectors.toList());
        ComponentBus componentBus = new ComponentBus();
        componentBus.setComponents(cps);
        componentBus.setEventName(this.beanName);
        componentBus.init();
        return componentBus;
    }

    @Override
    public Class<?> getObjectType() {
        return ComponentBus.class;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    @Override
    public void setBeanName(String name) {
        this.beanName = name;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}
